#ifdef WIN32
#include <windows.h>
#endif

#include <GL/glew.h>
#include <iostream>
#include "mesh/Material.h"

using namespace std;

Material::Material() {
	shininess = 0.2f;
}

void Material::use() {
	GLfloat blendFactors[3];
	GLint blendModes[3];

	GLint handle = shaderProgram->getHandle();
	GLint locBlendFactors = glGetUniformLocation(handle, "blendFactors");
	GLint locBlendModes = glGetUniformLocation(handle, "blendModes");
	GLint locMaterialColor = glGetUniformLocation(handle, "materialColor");
	GLint locNumTextures = glGetUniformLocation(handle, "numTextures");

	glUniform1i(locNumTextures, texrefs.size());
	glUniform4fv(locMaterialColor, 1, diffuse.getValue());

	for (unsigned int i = 0; i < texrefs.size(); i++) {
		blendFactors[i] = texrefs[i]->getBlendFactor();
		blendModes[i] = texrefs[i]->getBlendMode();
	}

	glUniform1fv(locBlendFactors, 3, blendFactors);
	glUniform1iv(locBlendModes, 3, blendModes);

	glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular.getValue());
	//glMaterialf(GL_FRONT_AND_BACK, GL_EMISSION, emmisive);
	glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);

	texrefs.size() > 0 ? glEnable(GL_TEXTURE_2D) : glDisable(GL_TEXTURE_2D);

	for (unsigned int i = 0; i < texrefs.size(); i++) {
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, texrefs[i]->getTexture()->getHandle());
	}
}

Material::~Material() {
	//cout << "Deleting Material " << name << endl;
	for (unsigned int i = 0; i < texrefs.size(); i++) {
		delete texrefs[i];
	}
}
